package com.interrupted;

import com.stream.User;

import java.util.concurrent.TimeUnit;

/**
 * 中断Demo
 * <p>
 * 当线程中断后再执行那种会抛出 InterruptedException 的方法，此时就会抛出 InterruptedException 并将中断标志位清除
 * 即调用 Thread.interrupted() 会返回false
 *
 * @author xudong
 */
public class InterruptedDemo {
	public static void main(String[] args) {
		// sleepThread不停的尝试睡眠
		Thread sleepThread = new Thread(() -> {
			while (true) {
				try {
					// 执行该方法阻塞后，会抛出InterruptedException，并清除中断标志位
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread() + " == " + Thread.currentThread().isInterrupted());
			}
		}, "SleepThread");

		sleepThread.setDaemon(true);

		sleepThread.start();
		sleepThread.interrupt();


		// busyThread不停的运行
		Thread busyThread = new Thread(() -> {
			for (int i = 0; i < 300; i++) {
				System.out.println(i + " - " + Thread.currentThread() + " == " + Thread.currentThread().isInterrupted());
			}
		}, "BusyThread");
		busyThread.setDaemon(true);
		busyThread.start();

		try {
			TimeUnit.MICROSECONDS.sleep(2);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		System.out.println("第一次休眠完毕");

		busyThread.interrupt();

		System.out.println("busyThread.isInterrupted() = " + busyThread.isInterrupted());
		// 休眠，让Thread充分运行
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		sleepThread.interrupt();
		System.out.println("sleepThread.isInterrupted() = " + sleepThread.isInterrupted());
		System.out.println("busyThread.isInterrupted() = " + busyThread.isInterrupted());
	}
}
